import { Router } from 'express';
import { MongoClient } from 'mongodb';

const router = Router();

// MongoDB 配置
const mongoUrl = 'mongodb://localhost:27017';
const dbName = 'risk_backend';
const collectionName = 'company_scores';

// 入驻企业总览数据
router.get('/', async (req, res) => {
  const client = new MongoClient(mongoUrl);

  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    // 获取每个企业最新的一条记录（按 LComNm 和 InfoPubDate 去重）
    const latestEnterpriseRecords = await collection
      .aggregate([
        { $sort: { LComNm: 1, InfoPubDate: -1 } },
        {
          $group: {
            _id: '$LComNm',
            doc: { $first: '$$ROOT' },
          },
        },
        { $replaceRoot: { newRoot: '$doc' } },
      ])
      .toArray();

    // 总企业数量
    const totalEnterprisesCount = latestEnterpriseRecords.length;

    // 企业列表（用于排行榜）
    const enterpriseList = latestEnterpriseRecords.map((item) => ({
      name: item.LComNm,
      revenue: item.Revenue,
      totalComprehensiveIncome: item.TotalComprehensiveIncome,
    }));

    // 新增企业数量（2024 年之后）
    const newEnterprisesCount = latestEnterpriseRecords.filter(
      (item) => new Date(item.InfoPubDate) >= new Date('2024-01-01')
    ).length;

    // 行业分布（按 RiskLevel 分组）
    const industryDistributionMap = new Map<string, number>();
    latestEnterpriseRecords.forEach((item) => {
      const key = item.RiskLevel || '未知';
      industryDistributionMap.set(key, (industryDistributionMap.get(key) || 0) + 1);
    });
    const industryDistribution = Array.from(industryDistributionMap, ([name, value]) => ({
      name,
      value,
    }));

    // 增长趋势（按月份统计）
    const monthCountMap = new Map<number, number>();
    latestEnterpriseRecords.forEach((item) => {
      const month = new Date(item.InfoPubDate).getMonth() + 1; // 0 = 一月
      monthCountMap.set(month, (monthCountMap.get(month) || 0) + 1);
    });
    const growthTrend = Array.from(monthCountMap.entries())
      .sort(([a], [b]) => a - b)
      .map(([, count]) => count);

    res.json({
      totalEnterprises: totalEnterprisesCount,
      enterpriseList,
      newEnterprises: newEnterprisesCount,
      industries: industryDistribution.length,
      growthTrend,
      industryDistribution,
    });
  } catch (error: any) {
    console.error('❌ 数据获取失败:', error);
    res.status(500).json({ message: '获取总览数据失败', error: error.message });
  } finally {
    await client.close();
  }
});

export default router;
